﻿using System.Globalization;
using System.Text.RegularExpressions;

namespace NetPublisher
{
    public class FtpConnectionString
    {
        private static readonly Regex ConnectionStringRegex = new Regex(@"FtpServer=(?<User>[\w-]+):(?<Pass>.+?)@(?<Server>[\w\.-]+)(:(?<Port>\d+))?/?(?<Path>.*)", RegexOptions.Compiled);

        private readonly string _userName;
        public string UserName
        {
            get { return _userName; }
        }

        private readonly string _password;
        public string Password
        {
            get { return _password; }
        }

        private readonly string _server;
        public string Server
        {
            get { return _server; }
        }

        private readonly string _path;
        public string Path
        {
            get { return _path; }
        }

        private readonly bool _isValid;
        public bool IsValid
        {
            get { return _isValid; }
        }

        private readonly int? _port;

        public int? Port
        {
            get { return _port; }
        }

		/// <summary>
		/// True to publish to this server.
		/// </summary>
    	public bool IsSelected { get; set; }

        public FtpConnectionString(string lineToParse)
        {
            if (lineToParse == @"@FtpServer=user:password@ftp.server.com/path")
                return;
            var match = ConnectionStringRegex.Match(lineToParse);
            if (!match.Success) return;
            _isValid = true;
            _userName = match.Groups["User"].Value;
            _password = match.Groups["Pass"].Value;
            _server = match.Groups["Server"].Value;
            _path = match.Groups["Path"].Value;
            if (match.Groups["Port"] != null && !string.IsNullOrWhiteSpace(match.Groups["Port"].Value))
                _port = int.Parse(match.Groups["Port"].Value, CultureInfo.InvariantCulture);
        }
    }
}
